#include "ejanimationwidget.h"
#include <QDebug>

EJAnimationWidget::EJAnimationWidget(QWidget *parent) : QWidget(parent)
{

}

void EJAnimationWidget::setAni(EJAnimation *ani)
{
    m_ani = ani;

    if (m_timer)
    {
        if (m_timer->isActive()) m_timer->stop();
        delete m_timer;
    }

    m_timer = new QTimer(this);
    int time = 1000 / ani->getFPS(); /*一帧所占用的时间*/

    connect(m_timer, SIGNAL(timeout()), this, SLOT(OnTimeOut()));

    m_timer->start(time);

    update();

}

void EJAnimationWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPixmap pixmap("://res/png/backgroup.png");

    int winw = width();
    int winh = height();
    int pw = pixmap.width(), ph = pixmap.height();

    for (int i = 0; i < winw / pw + (winw % pw != 0); i++)
    {
        for (int j = 0; j < winh / ph + (winh % ph != 0); j++)
        {
            painter.drawPixmap(i * pw, j * ph, pw, ph, pixmap);
        }
    }

    if (m_ani == nullptr) return;

    AnimationFrame *frame = m_ani->getFrame(m_index);

    painter.drawPixmap(winw / 2 - frame->off.x() , winh / 2 - frame->off.y(), frame->pixmap.width(), frame->pixmap.height(), frame->pixmap);
}

void EJAnimationWidget::OnTimeOut()
{
    m_index++;
    m_index %= m_ani->getFrameCount();
    update();
}
